package com.mvvm.ktnet.ui.amap

import android.annotation.SuppressLint
import android.content.Context
import android.location.*
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.annotation.RequiresApi


class GpsLocation(context: Context) {


    var mService = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager

    var startCount: (Int) -> Unit = {}

    var callBack = @RequiresApi(Build.VERSION_CODES.N)
    object : GnssStatus.Callback() {
        override fun onStarted() {
            super.onStarted()
        }

        override fun onStopped() {
            super.onStopped()
        }

        override fun onFirstFix(ttffMillis: Int) {
            super.onFirstFix(ttffMillis)
        }

        override fun onSatelliteStatusChanged(status: GnssStatus?) {
            super.onSatelliteStatusChanged(status)
            fetchCurGnssStatus(status)
        }
    }

    var listion = GpsStatus.Listener() {
        when (it) {
            GpsStatus.GPS_EVENT_STARTED -> {
            }
            GpsStatus.GPS_EVENT_STOPPED -> {
            }
            GpsStatus.GPS_EVENT_FIRST_FIX -> {
            }
            GpsStatus.GPS_EVENT_SATELLITE_STATUS -> {
                fetchCurGpsStatus()
            }
        }
    }

    var locationListener: LocationListener = object : android.location.LocationListener {
        override fun onLocationChanged(location: Location?) {

        }

        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
            when (status) {
                LocationProvider.AVAILABLE -> {

                }
                LocationProvider.OUT_OF_SERVICE -> {
                    gpsCount(0)
                }
                LocationProvider.TEMPORARILY_UNAVAILABLE -> {
                    gpsCount(0)
                }
            }

        }

        override fun onProviderEnabled(provider: String?) {

        }

        override fun onProviderDisabled(provider: String?) {
            gpsCount(0)
        }
    }

    init {


    }

    @SuppressLint("MissingPermission")
    fun addLis() {
        val bestProvider: String = mService.getBestProvider(getCriteria(), true)
        val location: Location = mService.getLastKnownLocation(bestProvider)
        gpsListener()
        mService.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 0f, locationListener)
    }


    private fun getCriteria(): Criteria {
        val criteria = Criteria()
        //设置定位精确度
        criteria.accuracy = Criteria.ACCURACY_FINE
        //设置是否要求速度
        criteria.isSpeedRequired = false
        //设置是否允许运营商收费
        criteria.isCostAllowed = false
        //设置是否需要方位信息
        criteria.bearingAccuracy = 0
        //设置是否需要海拔信息
        criteria.isAltitudeRequired = false
        //设置对电源的需求
        criteria.powerRequirement = Criteria.POWER_LOW
        return criteria
    }


    @SuppressLint("MissingPermission")
    fun gpsListener() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            mService.registerGnssStatusCallback(callBack)
        } else {
            mService.addGpsStatusListener(listion)
        }
    }

    private fun removeListen() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            mService.unregisterGnssStatusCallback(callBack)
        } else {
            mService.removeGpsStatusListener(listion)
        }
    }


    @RequiresApi(Build.VERSION_CODES.N)
    private fun fetchCurGnssStatus(status: GnssStatus?) {
        gpsCount(status?.satelliteCount ?: 0)
    }

    fun gpsCount(count: Int) {
        startCount.invoke(count)
    }


    @SuppressLint("MissingPermission")
    private fun fetchCurGpsStatus() {
        val mStatus = mService.getGpsStatus(null)
        //获取卫星颗数的默认最大值
        val maxSatellites = mStatus.maxSatellites
        //创建一个迭代器保存所有卫星
        val iters: Iterator<GpsSatellite> = mStatus.satellites.iterator()
        //卫星数
        var count = 0
        if (iters != null) {
            while (iters.hasNext() && count <= maxSatellites) {
                val s = iters.next()
                if (s.usedInFix()) {
                    count++
                }
            }
        }
        gpsCount(count)
    }


}